package com.guapi.controller;

import com.guapi.annotation.LoginRequired;
import com.guapi.entity.User;
import com.guapi.service.UserService;
import com.guapi.util.HostHolder;
import com.guapi.util.MailClient;
import com.guapi.util.MallUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;

@Controller
@RequestMapping(path = "/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Value("${second-mall.path.upload}")
    private String uploadPath;

    @Value("${second-mall.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    @Autowired
    private MailClient mailClient;


    @RequestMapping(path = "/setting", method = RequestMethod.GET)
    @LoginRequired
    public String getSettingPage(Model model) {
        User user = hostHolder.getUser();
        model.addAttribute("user", user);
        logger.warn(user.getAddress());
        return "/site/setting";
    }

    @RequestMapping(path = "/upload", method = RequestMethod.POST)
    @LoginRequired
    public String uploadHeader(MultipartFile headerImage, Model model) {

        if (headerImage == null) {
            model.addAttribute("error", "您还没有上传任何图片");
            return "/site/setting";
        }
        String filename = headerImage.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)) {
            model.addAttribute("error", "文件格式不正确");
            return "/site/setting";
        }

        filename = MallUtil.generateUUID() + suffix;

        File dest = new File(uploadPath + "/" + filename);
        try {
            headerImage.transferTo(dest);
        } catch (IOException e) {
            logger.error("上传文件失败" + e.getCause());
            throw new RuntimeException("上传文件失败，服务器发生异常!!" + e);
        }

        User user = hostHolder.getUser();

        String headerUrl = domain + contextPath + "/user/header/" + filename;

        userService.updateHeader(user.getId(), headerUrl);

        return "redirect:/index";
    }

    @RequestMapping(path = "/header/{filename}", method = RequestMethod.GET)
    public void getHeader(@PathVariable("filename") String filename, HttpServletResponse response) {

        filename = uploadPath + "/" + filename;

        String suffix = filename.substring(filename.lastIndexOf("."));

        response.setContentType("image/" + suffix);

        try (
                FileInputStream fis = new FileInputStream(filename);
                ServletOutputStream os = response.getOutputStream();
        ) {
            byte[] buffer = new byte[1024];
            int b = 0;
            while ((b = fis.read(buffer)) != -1) {
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("读取头像失败" + e.getCause());
        }
    }

    @RequestMapping(path = "/modify", method = RequestMethod.POST)
    public String modifyPassword(String userPassword, String userEmail, Model model) {
        Map<String, Object> map;
        if (hostHolder.getUser() != null) {
            map = userService.sendModifyPasswordMail(hostHolder.getUser(), userPassword, userEmail);
        } else {
            map = userService.sendModifyPasswordMail(userService.findUserByEmail(userEmail), userPassword, userEmail);
        }
        if (map == null || map.isEmpty()) {
            model.addAttribute("msg", "修改密码成功！");
            model.addAttribute("target", "/logout");
            //返回注册的操作结果
            return "/site/operate-result";
        } else {
            model.addAttribute("useMsg", map.get("useMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));
            return "/site/setting";
        }

    }

    @RequestMapping(path = "/modify/{username}/{password}", method = RequestMethod.GET)
    public String modifyPasswordResult(@PathVariable("username") String username, @PathVariable("password") String password, Model model) {
        User user = userService.findUserByName(username);
        int result = userService.updatePassword(user, password);
        if (result == 1) {
            model.addAttribute("msg", "您的密码已经修改，请牢记密码!");
            model.addAttribute("target", "/login");
            return "/site/operate-result";
        } else {
            model.addAttribute("msg", "出现了未知的错误，修改失败");
            model.addAttribute("target", "/user/setting");
            return "/site/operate-result";
        }
    }

    @RequestMapping(path = "/modify/address", method = RequestMethod.POST)
    public String modifyAddress(String address, Model model) {
        User user = hostHolder.getUser();
        if (user == null) {
            throw new IllegalArgumentException("用户未登录！");
        } else {
            userService.updateAddress(user.getId(), address);
            user=userService.findUserById(user.getId());
            hostHolder.setUser(user);
            model.addAttribute("user", user);
            return "/site/setting";
        }
    }
}
